//////////////////////////////////////////////////////////////////////////
//             Copyright 2013 TYPROTECH All Rights Reserved             //
//////////////////////////////////////////////////////////////////////////
/* =======================================================================
 * 系统名   : 安防平台管理系统
 * 子系统名 : 基础数据模块
 * Class名  : RoleSpecs
 * 概要     : 基础数据属性Specification类
 * 改版履历 : 
 * 版本     		日期        	作者名             备注
 * 1.0.0    2013.04.13  许智翔          初次作成
 * =======================================================================
 */
package com.framework.web.sys.repository.specifications;

import com.framework.core.util.LikePatternUtil;
import com.framework.core.util.StringUtil;
import com.framework.web.sys.domain.Organization;
import com.framework.web.sys.domain.User;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;

public class UserSpecs {

	/**
	 * 根据条件对角色进行查询分页操作
	 *
	 * @param user
	 * @return
	 */
	public static Specification<User> LikeUserName(
			final User user) {

		return new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root,
					CriteriaQuery<?> query, CriteriaBuilder builder) {
				Predicate predicate = builder.and();

				//组织机构
				if (user.getOrganization() != null) {
					Subquery<Long> orgSubquery = query.subquery(Long.class);
					Root<Organization> fromOrg = orgSubquery.from(Organization.class);
					orgSubquery.select(fromOrg.<Long>get("id"));
					orgSubquery.where(builder.like(fromOrg.<String>get("level"), LikePatternUtil.getEndLikePattern(user.getOrganization().getLevel())));
					Path<Long> path = root.get("orgId");
					// level
					predicate = builder.and(predicate, builder.in(path).value(orgSubquery));
				}

				// 用户名称
				if (StringUtil.isNotEmpty(user.getUserName())) {
					predicate = builder.and(predicate, builder.like(
							builder.lower(root.<String>get("userName")),
							LikePatternUtil.getLikePattern(user.getUserName())));
				}
				// 用户姓名
				if (StringUtil.isNotEmpty(user.getRealName())) {
					predicate = builder.and(predicate, builder.like(
							builder.lower(root.<String>get("realName")),
							LikePatternUtil.getLikePattern(user.getRealName())));
				}

				/*if (StringUtil.isNotEmpty(user.getLevel())) {
					predicate = builder.and(predicate, builder.like(
							builder.lower(root.<String>get("level")),
							LikePatternUtil.getEndLikePattern(user.getLevel())));
				}*/

				return predicate;
			}
		};
	}



}
